<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Chat</title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"
            integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
            crossorigin="anonymous"></script>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"/>

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
          integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"/>

    <!-- Awesome Font-->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
            integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
            crossorigin="anonymous"></script>
    <script src='https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js'></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js'></script>

    <script src='/rsocket-types.js'></script>
    <script src='/rsocket-flowable.js'></script>
    <script src='/rsocket-core.js'></script>
    <script src='/rsocket-websocket-client.js'></script>

    <style>
        .chats-row div {
            height: 50%;
            border: 1px solid #ddd;
            padding: 0px;
        }

        .media-object {
            max-width: 64px;
        }

        .current-chat {
            height: 100vh;
            border: 1px solid #ddd;
        }

        .current-chat-area {
            padding-top: 10px;
            overflow: auto;
            height: 92vh;
        }

        .chat-input {
            margin-top: 10px;
            margin-bottom: 10px;
            height: 8vh;
        }

        .chat-input textarea {
            width: 100%;
            border: none;
        }
        .chat-input button {
            position: absolute;
            right: 10px;
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12 current-chat">
            <div class="row current-chat-area">
                <div class="col-md-12">
                    <ul class="media-list">
                        <li th:each="message : ${messages}" class="media">
                            <div class="media-body">
                                <div class="media">
                                    <a class="pull-left" href="#">
                                        <img class="media-object img-circle "
                                             th:src="${message.getUser().getAvatarImageLink()}"/>
                                    </a>
                                    <div class="media-body" th:inline="none">
                                        <span th:utext="${message.getContent()}" th:remove="tag">title</span>
                                        <br/>
                                        <small class="text-muted"
                                               th:text="${message.getUser().getName()
                                               + ' | '
                                               + #temporals.format(message.getSent(), 'dd-MM-yyyy, HH:mm:ss')}"></small>
                                        <hr/>
                                    </div>
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="row chat-input">
                <div class="col-sm-12">
                    <textarea class="write_msg" placeholder="Type a message"></textarea>
                    <button class="msg_send_btn" type="button"><i class="fa fa-paper-plane-o" aria-hidden="true"></i></button>
                </div>
            </div>
        </div>
    </div>
</div>
<script th:inline="javascript">
    /*<![CDATA[*/
    var messageTemplate = _.template(
        '<li class="media">'
        + '<div class="media-body">'
        + '' + '<div class="media">'
        + '' + '' + '<a class="pull-left" href="#">'
        + '' + '' + '' + '<img class="media-object img-circle" src="<%= user.avatarImageLink %>"/>'
        + '' + '' + '</a>'
        + '' + '' + '<div class="media-body">'
        + '' + '' + '' + '<%= content %>'
        + '' + '' + '' + '<br/>'
        + '' + '' + '' + '<small class="text-muted"><%= user.name  %> | <%= moment(sent).format("DD-MM-YYYY, HH:mm:ss") %></small>'
        + '' + '' + '' + '<hr/>'
        + '' + '' + '</div>'
        + '' + '</div>'
        + '</div>' +
        '</li>',
        { 'imports': { 'moment': moment } });

    var user = { };
    $.ajax({
        url: 'https://randomuser.me/api/',
        dataType: 'json',
        success: function(data) {
            user.name = data.results[0].name.first + " " + data.results[0].name.last;
            user.avatarImageLink = data.results[0].picture.large;
        }
    });
    var lastMessageId = /*[[${lastMessageId}]]*/'';
    var mediaList = $('.media-list');
    var chatArea = $('.current-chat-area');
    var messageButton = $('.chat-input button');
    var messageInput = $('.chat-input textarea');

    chatArea.animate({scrollTop: mediaList.height()}, 1);

    const client = new rsocketCore.RSocketClient({
        transport: new rsocketWebSocketClient(
            {
                url: 'ws://localhost:8080/rsocket',
            },
            rsocketCore.BufferEncoders,
        ),
        setup: {
            dataMimeType: 'application/json',
            metadataMimeType: rsocketCore.MESSAGE_RSOCKET_COMPOSITE_METADATA.string,
            keepAlive: 5000,
            lifetime: 60000,
        },
    });

    client.connect()
        .then(rsocket => {
            var endpoint = "api.v1.messages.stream";

            rsocket.requestChannel(new rsocketFlowable.Flowable(source => {
                console.log("channel")
                source.onSubscribe({
                    cancel: () => {},
                    request: (n) => {}
                })
                messageButton.on("click", function() {
                    var content = messageInput.val();
                    messageInput.val("");
                    if (content) {
                        source.onNext({
                            data: Buffer.from(JSON.stringify({content: content , user: user, sent: new Date().toISOString()})),
                            metadata: rsocketCore.encodeAndAddWellKnownMetadata(
                                Buffer.alloc(0),
                                rsocketCore.MESSAGE_RSOCKET_ROUTING,
                                Buffer.from(String.fromCharCode(endpoint.length) + endpoint)
                            )
                        });
                    }
                });
            }))
                .subscribe({
                    onSubscribe: (s) => {
                        s.request(1000)
                    }
                });

            rsocket.requestStream({
                metadata: rsocketCore.encodeAndAddWellKnownMetadata(
                    Buffer.alloc(0),
                    rsocketCore.MESSAGE_RSOCKET_ROUTING,
                    Buffer.from(String.fromCharCode(endpoint.length) + endpoint)
                )
            })
                .subscribe({
                    onSubscribe: (s) => {
                        s.request(1000)
                    },
                    onNext: (e) => {
                        var v = JSON.parse(e.data);

                        mediaList.append(messageTemplate(v));
                        chatArea.stop();
                        chatArea.animate({scrollTop: mediaList.height()}, 500);
                    }
                });
        });

    /*]]>*/
</script>
</body>
</html>